package com.ftg.learn.mybatis.chapter1.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.Objects;

/**
 * @author kangjx
 * @createTime 2022/10/11
 */
public class SessionUtil {


    private static SqlSession session = null;

    {
        String resource = "mybatisconfig.xml";

        Reader inputStream = null;
        try {

            inputStream = Resources.getResourceAsReader(resource);
            SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
            SqlSessionFactory ssf = ssfb.build(inputStream);
            if(Objects.isNull(session)){
                session = ssf.openSession();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得session操作
     * @return
     */
    public static SqlSession getSession(){
        if(Objects.isNull(session)){
            String resource = "mybatisconfig.xml";

            Reader inputStream = null;
            try {

                inputStream = Resources.getResourceAsReader(resource);
                SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
                SqlSessionFactory ssf = ssfb.build(inputStream);
                session = ssf.openSession();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return session;
    }

}
